﻿
using FineUICore;

using System;
using System.Collections.Generic;
using System.Linq;
using BoYuanCore.DBServices.Base;
using BoYuanCore.Entities;
using BoYuanCore.Framework.MemoryCache;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;

namespace BoYuanCore.Web.Areas.Admin.Controllers
{
    public partial class SysRoleController : BaseController
    {
        private readonly ILogger<SysRoleController> _logger;
        private readonly ICachingProvider _iCachingProvider;

        public SysRoleController(ILogger<SysRoleController> logger, ICachingProvider iCachingProvider) : base(logger)
        {
            _logger = logger;
            _iCachingProvider = iCachingProvider;
        }

        #region ListPage
        // GET: Admin/SysRole
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ShowGrid(IFormCollection fc)
        {
            var keyword = fc["txb_keyword"].ToString().Trim();
            var query = DB.Select<Models.SysRoleVM>()
                .WhereIf(keyword.Length > 0, p=>p.RoleName.Contains(keyword) )
                .OrderBy(p => p.IsDel)
                .OrderBy(p => p.ID);

            var grid1 = UIHelper.Grid("Grid1");
            grid1.BindGrid(fc, "ddlPageSize", query);
            return UIHelper.Result();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult BtnDelete_Click(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids))
            {
                NotifyQuestion("请选择要删除的选中行！");
            }
            else
            {
                var tempStrs = ids.Substring(1).Split(',');
                List<long> idList=new List<long>();
                foreach (var str in tempStrs)
                {
                    if (long.TryParse(str.Trim(), out var idResult) && idResult!=1)//排除删除默认管理员权限角色
                    {
                        idList.Add(idResult);
                    }
                }

                if (idList.Count == 0)
                {
                    NotifyQuestion("请选择要删除的选中行！");
                }
                else
                {
                    DB.Delete<Entities.SysRole>().Where(p => idList.Contains(p.ID)).ExecuteAffrows();
                    foreach (var id in idList)
                    {
                        DBServices.SysModulePermissions.RemoveByCache(id, _iCachingProvider);
                    }
                    
                    AlertSuccess("删除成功！", false, "onGridBind()");
                }
            }
            return UIHelper.Result();
        }
        #endregion

        #region AddPage

        public ActionResult Add()
        {
            if (long.TryParse(Request.Query["id"], out long id))//编辑页面初始化
            {
                SysRole mo = FreeSqlHelper.GetModel<SysRole>(id);

                //左侧tree绑定
                ViewBag.Tree1DataSource = CreateTree(id).ToArray();
                mo.IsDel = !mo.IsDel;
                return View(mo);
            }
            else //添加页面
            {
                //左侧tree绑定
                ViewBag.Tree1DataSource = CreateTree().ToArray();
                ViewBag.isJsAdd = 1;//
                return View();//添加页面
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult BtnSave_OnClick(IFormCollection fc)
        {
            string nodeStr = fc["checkedNodes"];
            if (string.IsNullOrEmpty(nodeStr))
            {
                NotifyQuestion("请选择权限");
                return UIHelper.Result();
            }

            bool isEdit = long.TryParse(fc["f_ID"], out long ID);

            BoYuanCore.Entities.SysRole mo = new BoYuanCore.Entities.SysRole();
            mo.IsDel = !Convert.ToBoolean(fc["f_IsDel"]);
            mo.Remark = fc["f_Remark"];
            mo.RoleName = fc["f_RoleName"];


            string[] nodes = nodeStr.Substring(1).Split(',');
            List<SysModulePermissions> permissionsList = new List<SysModulePermissions>();

            if (!isEdit)//添加
            {
                var roleId = FreeSqlHelper.InsertModel(mo);
                if (roleId > 0)
                {
                    //页面关系
                    permissionsList.AddRange(nodes.Select(t => new SysModulePermissions() { PageID = Convert.ToInt64(t), RoleID = roleId }));
                    DB.Insert(permissionsList).ExecuteAffrows();
                    DBServices.SysModulePermissions.RemoveByCache(roleId, _iCachingProvider);

                    AlertInfor("添加成功", true);
                }
                else
                {
                    NotifyError("添加失败");
                }
            }
            else//修改
            {
                mo.ID = ID;
                int returnNum = FreeSqlHelper.UpdateModels(mo, p => new { p.IsDel, p.RoleName,p.Remark });
                if (returnNum > 0)
                {
                    //页面关系
                    DB.Delete<Entities.SysModulePermissions>().Where(p => p.RoleID == mo.ID).ExecuteAffrows();//删除旧的数据
                    permissionsList.AddRange(nodes.Select(t => new SysModulePermissions() { PageID = Convert.ToInt64(t), RoleID = mo.ID }));
                    DB.Insert(permissionsList).ExecuteAffrows();
                    DBServices.SysModulePermissions.RemoveByCache(mo.ID, _iCachingProvider);

                    AlertInfor("修改成功", true);
                }
                else
                {
                    NotifyError("修改失败");
                }
            }
            return UIHelper.Result();
        }
        #endregion

        #region tree
        /// <summary>
        /// 绑定tree
        /// </summary>
        /// <returns></returns>
        public static IList<TreeNode> CreateTree(long roleId = 0)
        {
            List<long> pageList = null;
            if (roleId > 0)
                pageList = DB.Select<SysModulePermissions>().Where(p => p.RoleID == roleId).ToList(p => p.PageID);

            var moduleList = DB.Select<SysModule>().WhereIf(!HaveButtonPermissions, p => string.IsNullOrEmpty(p.ButtonID)).ToList();
            IList<TreeNode> nodes = new List<TreeNode>();
            var mainNode = new TreeNode() {NodeID = "0", Text = "全选", Expanded = true};

            CreateTreeNodes(moduleList, mainNode, pageList);
            nodes.Add(mainNode);

            return nodes;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="moduleList"></param>
        /// <param name="parentNode"></param>
        public static void CreateTreeNodes(List<SysModule> moduleList, TreeNode parentNode, List<long> pageList)
        {
            var list = moduleList.Where(p => p.ParentID.ToString() == parentNode.NodeID).OrderBy(p => p.Sort).ToList();

            if (list == null || list.Count == 0) return;

            TreeNode node;
            foreach (var module in list)
            {
                node = new TreeNode();

                node.NodeID = module.ID.ToString();

                if (string.IsNullOrEmpty(module.ButtonID))//page 或 folder
                {
                    node.Text = module.PageTitle + (module.Remark.Length > 0 ? "(" + module.Remark + ")" : string.Empty) +
                                (module.IsHidden ? "<font color='red'>不显示</font>" : string.Empty);

                    if (!string.IsNullOrEmpty(module.Icon)) node.IconUrl = "/" + module.Icon;
                    if (!string.IsNullOrEmpty(module.FontIcon)) node.IconFont = (IconFont)Enum.Parse(typeof(IconFont), module.FontIcon);
                }
                else //button
                {
                    node.Text = "<font color='blue'>按钮</font> " + module.ButtonText + "(" + module.ButtonID + ")" +
                                (module.IsHidden ? "<font color='red'>不显示</font>" : string.Empty);
                    node.IconFont = IconFont.MousePointer;
                }

                node.Expanded = true;//默认节点都为展开

                if (pageList != null)
                    node.Checked = pageList.Contains(module.ID);

                CreateTreeNodes(moduleList, node, pageList);
                parentNode.Nodes.Add(node);
            }
        }


        #endregion
    }
}

